﻿using System.Linq;
using System.Reflection;

namespace Comdiv.QWeb.ViewEngine {
	public class QViewBinder {
		private QViewBindAttribute[] binds;

		public void Bind(IQView view, QViewContext context) {
			checkMembers(view);
			foreach (var binder in binds) {
				binder.Bind(view, context);
			}
		}

		private void checkMembers(IQView view) {
			binds = binds ??
			        view.GetType().GetMembers(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance |
			                                  BindingFlags.SetProperty | BindingFlags.SetField)
			        	.Where(x => 0 != x.GetCustomAttributes(typeof (QViewBindAttribute), true).Length)
			        	.Select(x =>
			        	        	{
			        	        		var result =
			        	        			x.GetCustomAttributes(typeof (QViewBindAttribute), true).First() as QViewBindAttribute;
			        	        		result.Member = x;
			        	        		return result;
			        	        	})
			        	.ToArray();
		}
	}
}